package com.micro.edu.rpc;

import com.micro.edu.service.IEmailRpc;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

@Service
public class EmailRpc implements IEmailRpc {

    private static final Logger LOG = LoggerFactory.getLogger(EmailRpc.class);

    @Value("${mail.username:403266439@qq.com}")
    private String username;

    @Value("${mail.message.subject:注册验证码}")
    private String subject;

    @Value("${mail.message.content:你的验证码为：%s ，%d 分钟内有效}")
    private String content;

    @Value("${code.expireTime:10}")
    private Integer expireTime = 10;

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public Integer send(String email, String code) {
        String format = String.format(content, code, expireTime);
        String content = "<h3 color='blue'>" + format + "</h3>";
        LOG.info("邮件信息：from:{} ,to:{} ,subject:{} ,content:{}", username, email, subject, content);
        try {
            send(username, email, subject, content);
            LOG.info("发送成功~~~~");
            return 1;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return 0;
        }
    }

    public void send(String from, String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
        } catch (Exception e) {
            LOG.error("发送 ~~ 简单邮件 ~~~发生异常", e);
            throw new RuntimeException(e);
        }
    }
}
